﻿using Npgsql;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
    class Database
    {
        NpgsqlConnection conn;
        string Server;
        string Port;
        string UserId;
        string Password;
        string DatabaseName;

        public Database()
        {
            Server = "localhost";
            Port = "5432";
            UserId = "postgres";
            Password = "root";
            DatabaseName = "anata_client";
        }

        public void Open()
        {
            try
            {
                string connstring = String.Format("Server={0};Port={1};User Id={2};Password={3};Database={4};", Server, Port, UserId, Password, DatabaseName);
                conn = new NpgsqlConnection(connstring);
                conn.Open();
            }
            catch (Exception msg)
            {
                MessageBox.Show(msg.ToString());
            }
        }

        public DataSet ExecuteQuery(string sql)
        {
            try
            {
                NpgsqlDataAdapter da = new NpgsqlDataAdapter(sql, conn);
                DataSet ds = new DataSet();

                ds.Reset();
                da.Fill(ds);

                return ds;
            }
            catch (Exception msg)
            {
                MessageBox.Show(msg.ToString());

                return null;
            }
        }

        public long ExecuteNonQuery(string sql)
        {
            try
            {
                long rowsAffected;
                NpgsqlCommand command = new NpgsqlCommand(sql, conn);

                rowsAffected = (long)command.ExecuteScalar();

                return rowsAffected;
            }
            catch (Exception msg)
            {
                MessageBox.Show(msg.ToString());

                return 0;
            }
        }

        public void ExecuteDelete(string sql)
        {
            try
            {
                NpgsqlCommand command = new NpgsqlCommand(sql, conn);

                command.ExecuteNonQuery();

            }
            catch (Exception msg)
            {
                MessageBox.Show(msg.ToString());
            }
        }

        public void Close()
        {
            try
            {
                conn.Close();
            }
            catch (Exception msg)
            {
                MessageBox.Show(msg.ToString());
            }
        }
    }
}
